
window.addEventListener("DOMContentLoaded", aios_init, false);
document.getElementById('search-box').parentNode.setAttribute('id', 'places-toolbar');

var aios_checkElems = new Array( 'aios-enableAutoClose', 'aios-rememberFolder', 'aios-scrollToFolder', 'aios-viewClose' );

var aios_managerWindow = document.getElementById('bookmarksPanel');
var aios_managerTree = document.getElementById("bookmarks-view");

if(document.getElementById('history-panel')) {
    aios_managerWindow = document.getElementById('history-panel');
    aios_managerTree = document.getElementById("historyTree");
}


//window.addEventListener("SidebarFocused", function(){ searchBookmarks(document.getElementById("search-box").value) } , false);
//window.addEventListener("SidebarFocused", bla , false);


function bla() {

    searchBookmarks(document.getElementById("search-box").value);

    //aios_init();

    //fireSidebarFocusedEvent();

    window.setTimeout(alertbla, 1000);
    
    //alert(document.getElementById("bookmarks-view").treeBoxObject.screenY);
    //alert(document.getElementById("bookmarks-view").treeBoxObject.y);
    //alert(document.getElementById("bookmarks-view").treeBoxObject.view.selection.currentIndex);

}

function alertbla() {

    //alert(document.getElementById("bookmarks-view").treeBoxObject.scrollTop);
    alert(aios_managerWindow.scrollY);

}


/*
	Initialisierung
		=> Aufruf durch onload in bm_hi.xul
*/
function aios_init() {
    // Menüleiste unter Mac OS X ausblenden
    aios_hideMacMenubar();

    // für CSS-Zwecke speichern
    aios_appInfo(aios_managerWindow);

    // Menüelemente synchronisieren
    aios_synchElements(aios_checkElems);

    // Standard-Click-Handler ändern
    if(aios_getBoolean("aios-enableAutoClose", "checked") || aios_getBoolean("aios-rememberFolder", "checked") || aios_getBoolean("aios-scrollToFolder", "checked")) {
        var prefstring, tbo, lastRowToSelect;

        if(document.getElementById('bookmarksPanel')) {
            aios_managerTree.setAttribute("onclick", 'aios_closeAutomatically(event, "bookmarks")');
            prefstring = "lastBookmarkFolder";
        }

        if(document.getElementById('history-panel')) {
            aios_managerTree.setAttribute("onclick", 'aios_closeAutomatically(event, "history")');
            prefstring = "lastHistoryFolder";
        }

        // zuletzt geöffneten Ordner markieren
        if(aios_getBoolean("aios-rememberFolder", "checked")) {
            if(aios_gPrefBranch.prefHasUserValue(prefstring)) {
                lastRowToSelect = aios_gPrefBranch.getIntPref(prefstring);
                tbo = aios_managerTree.treeBoxObject;
                setTimeout(aios_selectFolder, 10, lastRowToSelect, tbo);
            }
        }
    }

    // Chronik
    if(document.getElementById('history-panel')) {

        var viewButton = document.getElementById("viewButton");
        var popUp = viewButton.firstChild;

        // dem "Extras"-Menü den Separator und die drei Menüpunkte hinzufügen
        if(document.getElementById("bylastvisited")) {
            popUp.appendChild(document.getElementById('close-separator'));
            document.getElementById('close-separator').hidden = false;

            popUp.appendChild(document.getElementById('aios-enableAutoClose'));
            popUp.appendChild(document.getElementById('aios-rememberFolder'));
            popUp.appendChild(document.getElementById('aios-scrollToFolder'));

            popUp.appendChild(document.getElementById('close-separator').cloneNode(true));

            popUp.appendChild(document.getElementById('aios-viewClose'));
        }

        viewButton.removeAttribute('accesskey');
        viewButton.removeChild(document.getElementById('viewPopUp'));
    }

    var aios_inSidebar = (top.document.getElementById('sidebar-box')) ? true : false;

    var aios_prefstring = "bm";
    if(document.getElementById('history-panel')) aios_prefstring = "hi";

    try {
        var enable_layout = aios_gPrefBranch.getBoolPref(aios_prefstring + ".layout");
        var enable_layoutall = aios_gPrefBranch.getBoolPref(aios_prefstring + ".layoutall");
    }
    catch(e) {
        return false;
    }

    if((enable_layout && aios_inSidebar) || enable_layoutall) aios_sidebarLayout();
}


/*
	aktiviert das an die Sidebar angepasste Layout
		=> Aufruf durch aios_init()
*/
function aios_sidebarLayout() {
    var attr, i;

    // CSS für Sidebar-Optimierungen aktivieren
    aios_managerWindow.setAttribute('aiosLayout', true);
    aios_addCSS("places.css", aios_managerWindow);

    var searchObj = document.getElementById("search-box");

    // Tooltip, focus- und blur-Funktionen hinzufügen
    // 	=> erst hier bei init(), weil es sonst Skript-Fehler geben würde
    // 	=> nicht aktivieren in Verbindung mit Bookmark Duplicate Detector
    if(typeof Bookmarkdd != "object") {
        searchObj.setAttribute('onfocus', 'aios_focusBlurText("focus");');
        searchObj.setAttribute('onblur', 'aios_focusBlurText("blur");');
    }

    if(document.getElementById("closeFolder") && document.getElementById("closeFolder").localName == "button") {
        var closeButton = document.getElementById("closeFolder");
        attr = closeButton.attributes;

        // alten <button> entfernen
        closeButton.parentNode.removeChild(closeButton);

        var new_closeButton = document.createElement("toolbarbutton");

        // alle Attribute des alten Buttons übernehmen
        for(i = 0; i < attr.length; i++) {
            new_closeButton.setAttribute(attr[i].name, attr[i].value);
        }

        // neuen <toolbarbutton> einfügen
        searchObj.parentNode.appendChild(new_closeButton);
    }

    // falls der "Tools"-Button ein <button> ist (FF >= 1.5), diesen durch einen <toolbarbutton> ersetzen
    if(document.getElementById("viewButton") && document.getElementById("viewButton").localName == "button") {
        var viewButton = document.getElementById("viewButton");
        var popUp = viewButton.firstChild.cloneNode(true);
        attr = viewButton.attributes;

        // alten <button> entfernen
        viewButton.parentNode.removeChild(viewButton);

        var new_viewButton = document.createElement("toolbarbutton");

        // alle Attribute des alten Buttons übernehmen
        for(i = 0; i < attr.length; i++) {
            new_viewButton.setAttribute(attr[i].name, attr[i].value);
        }

        // neuen <toolbarbutton> einfügen
        new_viewButton.appendChild(popUp);
        searchObj.parentNode.appendChild(new_viewButton);
    }
}


/*
"Suchbegriff" im Suchfeld anzeigen oder verbergen
		=> Aufruf durch onfocus() und onblur() des Suchfeldes
*/
function aios_focusBlurText(mode) {
    if(aios_appOS == "Darwin") return;

    var searchObj = document.getElementById("search-box");
    var strings = document.getElementById("propSetStrings");
    var blurText = strings.getString('bm_hi.search.blur');

    if(mode == "focus" && searchObj.value == blurText) {
        searchObj.className = "";
        searchObj.value = "";
    }
    else if(mode == "blur" && searchObj.value == "") {
        searchObj.className = "blur";
        searchObj.value = blurText;
    }
}


function aios_selectFolder(index, tbo) {
    if (tbo.view.rowCount >= index) {
        tbo.view.selection.select(index);
        // check if we really need to scroll
        if(tbo.view.rowCount > tbo.getPageLength()) tbo.scrollToRow(index);
        tbo.ensureRowIsVisible(index);
    }
}


function aios_closeAutomatically(aEvent, sidebarType) {

    if(!aEvent || !sidebarType || (sidebarType != "history" && sidebarType != "bookmarks")) {
        return;
    }

    // Rechts-Klick nicht beachten
    if (aEvent.button == 2) {
        return;
    }

    // kein Links-Klick => Standardaktion
    const dotoggle = (aEvent.button == 0) ? true : false;

    const tree = aios_managerTree;
    const tbo = aios_managerTree.treeBoxObject;

    // Klick auf + Zeichen ignorieren
    var row = {}, col = {}, obj = {};
    tbo.getCellAt(aEvent.clientX, aEvent.clientY, row, col, obj);

    if(row.value == -1 || obj.value == "twisty") {
        return;
    }

    var mouseInGutter = false;
    var x = { }, y = { }, w = { }, h = { };
    tbo.getCoordsForCellItem(row.value, col.value, "image", x, y, w, h);
    mouseInGutter = aEvent.clientX < x.value;

    const tboView = tbo.view;
    const modifKey = aEvent.shiftKey || aEvent.ctrlKey || aEvent.altKey || aEvent.metaKey  || aEvent.button == 1;
    row = row.value;
    const isContainer = tboView.isContainer(row);

    // Ordner schließen
    if (dotoggle && isContainer && !modifKey) {

        // Standardvorgang: öffnet oder schliesst den Ordner
        tboView.toggleOpenState(row);


        // zuletzt ausgewählten Ordner merken
        if(aios_getBoolean("aios-rememberFolder", "checked")) {
            switch(sidebarType) {
                case "bookmarks":
                    aios_gPrefBranch.setIntPref("lastBookmarkFolder", tree.currentIndex);
                    break;

                case "history":
                    aios_gPrefBranch.setIntPref("lastHistoryFolder", tree.currentIndex);
                    break;
            }
        }


        // andere Ordner schließen
        if(aios_getBoolean("aios-enableAutoClose", "checked")) {
            // Eltern-Ordner suchen und in Array packen
            var parents = new Array();
            while(row != -1) {
                parents.push(row);
                row = tboView.getParentIndex(row);
            }
            parents.reverse();

            // Zeilen durchlaufen...
            for(var i = tboView.rowCount - 1; i >= 0; i--) {
                // Eltern-Ordner geöffnet lassen => Element aus Array entfernen
                if(parents.length > 0 && parents[parents.length - 1] == i) {
                    parents.pop();
                }
                // andere Ordner schließen
                else {
                    if(tboView.isContainer(i) && tboView.isContainerOpen(i)) {
                        tboView.toggleOpenState(i);
                    }
                }
            }
        }


        // zum geöffneten Ordner springen/scrollen
        if(aios_getBoolean("aios-scrollToFolder", "checked") &&  (tboView.rowCount > tbo.getPageLength())) {
            tbo.scrollToRow(tree.currentIndex);
        }
        // scrollt zum Index nur wenn nötig
        tbo.ensureRowIsVisible(tree.currentIndex);

        return;
    }

    // Ordner öffnen
    if(!mouseInGutter && aEvent.originalTarget.localName == "treechildren" && (aEvent.button == 0 || aEvent.button == 1)) {
        // Clear all other selection since we're loading a link now. We must
        // do this *before* attempting to load the link since openURL uses
        // selection as an indication of which link to load.
        tboView.selection.select(row);
        var hasPlaces = (typeof(PlacesUIUtils) == "object" || typeof(PlacesUtils) == "object");

        if(hasPlaces&& typeof(PlacesUIUtils.openNodeWithEvent) == "function") {
            if(!isContainer) {
                PlacesUIUtils.openNodeWithEvent(tree.selectedNode, aEvent);
            }
            else {
                PlacesUIUtils.openContainerNodeInTabs(tree.selectedNode, aEvent);
            }
            return;
        }

        if(hasPlaces && typeof(PlacesUtils.openNodeWithEvent) == "function") {
            PlacesUtils.openNodeWithEvent(tree.selectedNode, aEvent);
            return;
        }

        if(tree.controller && typeof(tree.controller.openSelectedNodeWithEvent) == "function") {
            tree.controller.openSelectedNodeWithEvent(aEvent);
            return;
        }

        if(sidebarType == "bookmarks" && typeof(tree.openItemClick) == "function") {
            tree.openItemClick(aEvent, 1);
            return;
        }

        if(sidebarType == "history" && typeof(openURL) == "function") {
            openURL(aEvent);
            return;
        }
    }
}


function aios_closeFolder() {
    var aView = aios_managerTree.treeBoxObject.view;

    // zuletzt geöffneten Ordner "vergessen"
    try {
        if(document.getElementById('bookmarksPanel')) aios_gPrefBranch.clearUserPref("lastBookmarkFolder");
        if(document.getElementById('history-panel')) aios_gPrefBranch.clearUserPref("lastHistoryFolder");
    }
    catch(e) {  }

    // Ordner schließen
    if (aView) {
        for(var i = aView.rowCount - 1; i >= 0; i--) {
            if(aView.isContainer(i) && aView.isContainerOpen(i)) aView.toggleOpenState(i);
        }
    }
}